/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.seari.controller;

import com.seari.bean.*;
import com.seari.pojo.DataGridBean;
import com.seari.pojo.MessageBean;
import com.seari.pojo.QueryUser;
import com.seari.service.*;
import com.seari.utils.*;

import io.jsonwebtoken.Claims;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 *
 * @author whl
 */
@Controller
@RequestMapping("account")
public class DeviceAccountController
{
    @Autowired
    private MaterialCaregoryService materialCaregoryService;

    @Autowired
    private MaterialCaregoryAttrService materialCaregoryAttrService;

    @Autowired
    private MaterialCaregoryAttrValueService materialCaregoryAttrValueService;

    @Autowired
    private ProductService productService;

    @Autowired
    private DevLifeService devLifeService;

    @Autowired
    private UserService userService;

    @RequestMapping("getDeviceList")
    @ResponseBody
    public DataGridBean<Map<String,String>> getDeviceList(HttpServletRequest req)
    {
        DataGridBean<Map<String,String>> grid = new DataGridBean<Map<String,String>>();
        String fMcId = req.getParameter("fMcId");
        String stationId = req.getParameter("stationId");
        String keyword = req.getParameter("keyword");
        String currPage = req.getParameter("page");
        String pageSize = req.getParameter("limit");

        Map<String,Object> map = new HashMap<>();
        if(StringUtils.isNotBlank(fMcId))
        {
            map.put("fMcId",fMcId);
        }
        if(StringUtils.isNotBlank(stationId))
        {
            map.put("stationId",stationId);
        }
        if(StringUtils.isNotBlank(keyword))
        {
            map.put("keyword",keyword);
        }

        if(StringUtils.isNotBlank(currPage) && StringUtils.isNotBlank(pageSize))
        {
            map.put("start",(Integer.parseInt(currPage) - 1) * Integer.parseInt(pageSize));
            map.put("limit",Integer.parseInt(pageSize));
        }
        List<Map<String,String>> accountList = materialCaregoryAttrValueService.getDeviceAccountByFMcId(map);
        grid.setRows(accountList);
        grid.setTotal(materialCaregoryAttrValueService.getAccountListCount(map));
        return  grid;
    }

    @RequestMapping("deleteAttrValue")
    @ResponseBody
    public MessageBean deleteAttrValue(HttpServletRequest request) {
        MessageBean mb = new MessageBean();
        String fProductId = request.getParameter("fProductId");

        if(StringUtils.isBlank(fProductId)) {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }

        DevLifeBean devLifeBean = new DevLifeBean();
        devLifeBean.setProductId(fProductId);
        int lifeCount = devLifeService.deleteDevLifeCircleById(devLifeBean);
        if(lifeCount > 0){
            Product product = new Product();
            product.setfProductId(fProductId);
            int resCount = productService.deleteProductById(product);
            if(resCount > 0){
                MaterialCaregoryAttrVaule materialCaregoryAttrVaule = new MaterialCaregoryAttrVaule();
                materialCaregoryAttrVaule.setfProductId(fProductId);
                int delCount = materialCaregoryAttrValueService.deleteAttrValueByProductId(materialCaregoryAttrVaule);
                if(delCount > 0){
                    mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
                    mb.setMessage("删除设备成功");
                } else {
                    mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                    mb.setMessage("删除设备失败");
                }
            } else {
                mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
                mb.setMessage("删除设备失败");
            }
        } else {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("删除设备失败");
        }
        return  mb;
    }

    @RequestMapping("updateAttrValue")
    @ResponseBody
    public MessageBean updateAttrValue(HttpServletRequest request) {
        String userId = ParseUtils.getUidFromToken(request,userService);

        MessageBean mb = new MessageBean();
        String fMcId = request.getParameter("fMcId");
        String fProductId = request.getParameter("fProductId");

        if(StringUtils.isBlank(fProductId)) {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }else{
            if(StringUtils.isBlank(fMcId)){
                Product product = new Product();
                product.setfProductId(fProductId);
                List<Product> productList = productService.getProductById(product);
                if(productList != null && productList.size()>0){
                    fMcId = productList.get(0).getfMcId();
                }
            }
        }

        //获取字段的主键值,封装成Map
        MaterialCaregoryAttr mc = new MaterialCaregoryAttr();
        mc.setfMcId(fMcId);
        List<MaterialCaregoryAttr> mcAttrList = materialCaregoryAttrService.getFMcAttrByParams(mc);
        Map<String,String> mcAttrMap = new HashMap<>();
        for (MaterialCaregoryAttr mcAttr : mcAttrList) {
            mcAttrMap.put(mcAttr.getfCaCode(),mcAttr.getfCaId());
        }

        //获取所以字段和字段值，封装成Product和List<MaterialCaregoryAttrVaule>
        Map<String, String[]> properties = request.getParameterMap();//把请求参数封装到Map<String, String[]>中
        Map<String, String> returnMap = new HashMap<>();
        String name = "";
        String value = "";
//        String fProductId = Tools.get32UUID();
        Product product = new Product();
        product.setfProductId(fProductId);
        product.setfMcId(fMcId);
        List<MaterialCaregoryAttrVaule> mcAttrValueList = new ArrayList<>();
        MaterialCaregoryAttrVaule mcAttrValue = null;
        for (Map.Entry<String, String[]> entry : properties.entrySet()) {
            name = entry.getKey();
            if(!"fMcId".equals(name) && !"fProductId".equals(name)){
                mcAttrValue = new MaterialCaregoryAttrVaule();
                String[] values = entry.getValue();
                if (null == values) {
                    value = "";
                } else if (values.length > 1) {
                    for (int i = 0; i < values.length; i++) { //用于请求参数中有多个相同名称
                        value = values[i] + ",";
                    }
                    if(value != "" && value != null){
                        value = value.substring(0, value.length() - 1);
                    }
                } else {
                    value = values[0];//用于请求参数中请求参数名唯一
                }
                returnMap.put(name, value);
                if("ZC_CODE".equals(name)){
                    product.setZcCode(value);//资材编码(实际编码)
                }else if("ZC_NAME".equals(name)){
                    product.setfProductName(value);
                    product.setfProductShowName(value);
                }else if("STATION_ID".equals(name)){
                    product.setStationId(value);
                }
                mcAttrValue.setfProductId(fProductId);
                mcAttrValue.setfCaId(mcAttrMap.get(name));
                mcAttrValue.setfMcaValue(value);
                mcAttrValueList.add(mcAttrValue);
            }
        }

        //设置站点ID
        for(MaterialCaregoryAttrVaule attrValue : mcAttrValueList){
            attrValue.setStationId(product.getStationId());
        }

        //保存到数据库
        int resultCountProduct = productService.updateProductById(product);
        int resultCountMcAttrValue = 0;
        MaterialCaregoryAttrVaule materialCaregoryAttrVaule = new MaterialCaregoryAttrVaule();
        materialCaregoryAttrVaule.setfProductId(fProductId);
        int delCount = materialCaregoryAttrValueService.deleteAttrValueByProductId(materialCaregoryAttrVaule);
        if(delCount > 0){
            resultCountMcAttrValue = materialCaregoryAttrValueService.addMcAttrValueBatch(mcAttrValueList);
        }

        if(resultCountProduct > 0 && resultCountMcAttrValue > 0) {
            DevLifeBean devLifeBean = new DevLifeBean();
            devLifeBean.setProductId(fProductId);
            devLifeBean.setLifeStatus("1");
            devLifeBean.setRemark(product.getfProductShowName());
            devLifeBean.setCureateUserId(userId);
            devLifeService.saveDevLifeInfo(devLifeBean);//保存到设备生命周期表中
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("修改资材属性值成功");
        } else {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("修改资材属性值失败");
        }

        return  mb;
    }

    /**
     * 导出设备。
     *
     * @param response
     * @throws Exception
     * @see
     */
    @RequestMapping(value = "/exportDevList")
    public void exportDevList(HttpServletRequest request,HttpServletResponse response)
            throws Exception
    {
        // 获取参数
        String fMcId = request.getParameter("fMcId");
        String stationId = request.getParameter("stationId");
        String keyword = request.getParameter("keyword");
        String fields = request.getParameter("fields");
        if(fields != null && fields != ""){
            String[] fieldArray = fields.split(",");
            MaterialCaregoryAttr mcAttr = new MaterialCaregoryAttr();
            mcAttr.setfMcId(fMcId);
            // 获得资材分类属性数据
            List<MaterialCaregoryAttr> data = materialCaregoryAttrService.getFMcAttrByParams(mcAttr);
            Map<String,String> map = new HashMap<>();
            if(data != null){
                for(MaterialCaregoryAttr attr : data){
                    map.put(attr.getfCaCode(),attr.getfCaShowName());
                }
            }
            // 返回文件的文件名
            MaterialCaregory materialCaregory = new MaterialCaregory();
            materialCaregory.setfMcId(fMcId);
            materialCaregory = materialCaregoryService.getFMcByFMcId(materialCaregory);
            String fileName = "设备台账";
            String fMcShowName = "";
            if(materialCaregory != null){
                fMcShowName = materialCaregory.getfMcShowName();
            }
            fileName = fileName + "_" + fMcShowName + ".xls";
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置返回消息头
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType(
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            // 获取返回的流
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            // 新建excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 装载数据
            setDatas(workbook, fieldArray, map, fMcId, stationId, keyword, fMcShowName);
            // 回写文件
            ExportExcelUtil.writeFile(response, out, workbook);
        }
    }

    /**
     * 把数据库查询出来的数据填入excel中。
     *
     * @param workbook
     * @param map
     * @see
     */
    public void setDatas(HSSFWorkbook workbook, String[] fieldArray, Map<String,String> map,
                           String fMcId,String stationId,String keyword, String fMcShowName) throws Exception {
        int length = fieldArray.length;
        if (length != 0){
            // 添加sheet
            HSSFSheet sheet1 = workbook.createSheet("设备台账");

            // 在sheet1中添加第一行，将类型名称填入
            HSSFRow row = sheet1.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue(fMcShowName);
            // 合并单元格
            sheet1.addMergedRegion(new CellRangeAddress(0, 0, 0, length));
            // 遍历，将字段名称填入sheet1第二行,将字段编码放入sheet2第一行
            HSSFRow row1 = sheet1.createRow(1);
            String sql = "SELECT * FROM (SELECT a.F_MC_ID, v.F_PRODUCT_ID, v.STATIONID,";
            for (int i = 0; i < length; i++ )
            {
                // 将字段名称填入sheet1第二行
                Cell cellTemp1 = row1.createCell(i);
                cellTemp1.setCellValue(map.get(fieldArray[i]));
                sql += "MAX(IF(a.F_CA_SHOW_NAME = '" + map.get(fieldArray[i]) +
                       "',v.F_MCA_VALUE,0)) AS '" + fieldArray[i] + "',";
            }
            sql = sql.substring(0,sql.length()-1);
            sql += "FROM tobj_material_caregory_attr a " +
                    "LEFT JOIN tobj_mc_attribute_value v ON a.F_CA_ID = v.F_CA_ID " +
                    "WHERE a.F_CA_ENABLED='1' and !ISNULL(v.F_PRODUCT_ID) and a.F_MC_ID = '" + fMcId + "' " +
                    "GROUP BY v.F_PRODUCT_ID,v.STATIONID) w WHERE 1=1 ";

            if(Tools.notEmpty(keyword)){
                sql += "AND (w.ZC_CODE LIKE CONCAT(CONCAT('%', '" + keyword + "'),'%') OR "+
                        "w.ZC_NAME LIKE CONCAT(CONCAT('%', '" + keyword + "'),'%') OR " +
                        "w.ZC_SUB_TYPE_ID LIKE CONCAT(CONCAT('%', '" + keyword + "'),'%') ) ";
            }

            if(Tools.notEmpty(stationId)){
                sql += "AND w.STATION_ID = '" + stationId + "' ";
            }

            List<Map<String,String>> mapList = materialCaregoryAttrValueService.superSelect(sql);
            for (int a = 0;a < mapList.size(); a++) {
                HSSFRow dataRow = sheet1.createRow(a+2);
                for (int i = 0; i < length; i++ ){
                    Cell cellTemp = dataRow.createCell(i);
                    cellTemp.setCellValue(mapList.get(a).get(fieldArray[i]));
                }
            }
        }
    }

    @RequestMapping("getAllHostList")
    @ResponseBody
    public DataGridBean<Map<String,String>> getAllHostList(HttpServletRequest req)
    {
        DataGridBean<Map<String,String>> grid = new DataGridBean<Map<String,String>>();
        String productId = req.getParameter("productId");
        Map<String,String> map = new HashMap<>();
        map.put("productId",productId);
        List<Map<String,String>> hostList = productService.showAllZabbixHosts(map);
        grid.setRows(hostList);
        if(hostList != null && hostList.size()>0){
            grid.setTotal(hostList.size());
        }else{
            grid.setTotal(0);
        }
        return  grid;
    }

    @RequestMapping("getHostByProductId")
    @ResponseBody
    public Map<String,Object> getHostByProductId(HttpServletRequest req)
    {
        Map<String,Object> result = new HashMap<>();
        RlProductHost rlProductHost = new RlProductHost();
        String productId = req.getParameter("productId");
        rlProductHost.setProductId(productId);
        List<RlProductHost> rlProductHostList = productService.getRlProductHost(rlProductHost);
        if(rlProductHostList != null && rlProductHostList.size()>0){
            result.put("rlProductHost",rlProductHostList.get(0));
            result.put("code","success");
        }else{
            result.put("code","empty");
        }
        return  result;
    }

    @RequestMapping("saveRlHost")
    @ResponseBody
    public MessageBean saveRlHost(HttpServletRequest req)
    {
        MessageBean mb = new MessageBean();
        // 获取参数
        String id = req.getParameter("id");
        String productId = req.getParameter("productId");
        String hostId = req.getParameter("hostId");
        if(StringUtils.isBlank(productId) || StringUtils.isBlank(hostId))
        {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }

        int resultNum = 0;
        RlProductHost rlProductHost = new RlProductHost();
        rlProductHost.setHostId(Integer.parseInt(hostId));
        rlProductHost.setProductId(productId);
        if(StringUtils.isBlank(id)){
            id = UUID.randomUUID().toString().replace("-","");
            rlProductHost.setId(id);
            resultNum = productService.addRlProductHost(rlProductHost);
        }else {
            rlProductHost.setId(id);
            resultNum = productService.updateRlProductHost(rlProductHost);
        }

        if(resultNum > 0) {
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("绑定设备成功");
        } else {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("绑定设备失败");
        }
        return  mb;
    }

    @RequestMapping("unBindDeviceRlHost")
    @ResponseBody
    public MessageBean unBindDeviceRlHost(HttpServletRequest req)
    {
        MessageBean mb = new MessageBean();
        // 获取参数
        String id = req.getParameter("id");
        if(StringUtils.isBlank(id))
        {
            //表单验证
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("表单信息不完整");
            return mb;
        }

        int resultNum = 0;
        RlProductHost rlProductHost = new RlProductHost();
        if(StringUtils.isNoneBlank(id)){
            rlProductHost.setId(id);
            resultNum = productService.deleteRlProductHost(rlProductHost);
        }

        if(resultNum > 0) {
            mb.setCode(StringHelper.MESSAGE_TYPE_SUCCESS);
            mb.setMessage("解除绑定设备成功");
        } else {
            mb.setCode(StringHelper.MESSAGE_TYPE_ERROR);
            mb.setMessage("解除绑定设备失败");
        }
        return  mb;
    }
}
